package com.heima.comment.Service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.AliyunGreenTemplate;
import com.heima.comment.Service.CommentService;
import com.heima.comment.pojo.ApComment;
import com.heima.feign.ApUserClient;
import com.heima.model.apuser.entity.ApUser;
import com.heima.model.comment.dto.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.WmThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApUserClient apUserClient;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AliyunGreenTemplate aliyunGreenTemplate;

    @Override
    public ResponseResult save(CommentSaveDto dto) {
        if (dto.getArticleId() == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        Long userId = WmThreadLocalUtil.get();
        //用户需要登录才能发表评论
        if (userId == null || userId == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //阿里云审核内容是否违规
        Map<String, String> request = aliyunGreenTemplate.greenTextScan(dto.getContent());
        String suggestion = request.get("suggestion");
        if (!"pass".equals(suggestion)){
            return  ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"内容审核未通过");
        }

        //查看redis有没有用户头像 昵称数据
        //redis 缓存数据String结构   key为user_data_用户id    value为对象序列化后的json
        String key = "user_data_" + userId;
        String json = redisTemplate.opsForValue().get(key);

        ApUser apUser = null;
        //用户数据在缓存中没有
        if (json == null) {
            //远程调用用户资源 拿到用户的昵称和头像
            apUser = apUserClient.getUser(userId);
            //将数据保存到redis中
            redisTemplate.opsForValue().set(key, JSON.toJSONString(apUser));
        }

        //将数据保存到mongodb评论表中
        ApComment apComment = new ApComment();
        apComment.setUserId(userId);
        apComment.setNickName(apUser.getNicknme());
        apComment.setImage(apUser.getImage());
        apComment.setTargetId(dto.getArticleId()+"");
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        //保存到mongodb中
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(apComment);
    }
}
